package OssClinet

import (
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"io"
	"os"
)

type Bucket struct {
	raw *oss.Bucket
}

func (b *Bucket) PutObjectFromFile(key, localPath string) error {
	f, err := os.Open(localPath)
	if err != nil {
		return err
	}
	defer f.Close()
	return b.raw.PutObject(key, f)
}

func (b *Bucket) GetObjectToFile(key, localPath string) error {
	rc, err := b.raw.GetObject(key)
	if err != nil {
		return err
	}
	defer rc.Close()

	f, err := os.Create(localPath)
	if err != nil {
		return err
	}
	defer f.Close()

	_, err = io.Copy(f, rc)
	return err
}

func (b *Bucket) ListObjects(prefix string, maxKeys int, marker string) ([]oss.ObjectProperties, error) {
	options := []oss.Option{}
	if prefix != "" {
		options = append(options, oss.Prefix(prefix))
	}
	if maxKeys > 0 {
		options = append(options, oss.MaxKeys(maxKeys))
	}
	if marker != "" {
		options = append(options, oss.Marker(marker))
	}

	res, err := b.raw.ListObjects(options...)
	if err != nil {
		return nil, err
	}
	return res.Objects, nil
}

func (b *Bucket) DeleteObject(key string) error {
	return b.raw.DeleteObject(key)
}
